from flask import render_template, g, redirect, request, jsonify, current_app, abort

from info import db, constants
from info.models import User, News, Category
from info.modules.profile import profile_blu
from info.utils.common import set_func
from info.utils.image_storage import storage
from info.utils.response_code import RET



@profile_blu.route('/unselect', methods=['POST'])
@set_func
def unselect():
    """
    用户详情页取消关注
    :return:
    """
    user = g.user

    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录')

    # 1.接收两个参数,准备取消关注的作者的id
    other_id = request.json.get('user_id')
    action = request.json.get('action')

    # 2.校验参数
    if not other_id:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    try:
        other_id = int(other_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    if action not in ('unfollow', 'follow'):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    # 3.业务逻辑处理
    # 根据作者的id查询出作者
    try:
        other = User.query.get(other_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据查询错误')

    if not other:
        return jsonify(errno=RET.NODATA, errmsg='用户不存在')


    if action == 'unfollow':  # 说明要取消关注
        # 把作者从用户的关注列表删除
        user.followed.remove(other)

    else:  # 说明要 关注作者
        # 把作者添加到用户的关注列表里
        user.followed.append(other)


    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='操作失败')

    return jsonify(errno=RET.OK, errmsg='OK')



@profile_blu.route('/other_news_list')
def other_news_list():
    """
    其它用户发布新闻信息展示
    :return:
    """

    # 1.接收参数,两个参数,一个是其它用户的id,还有一个是当前页数,第几页
    p = request.args.get('p')
    other_id = request.args.get('user_id')

    # 2.校验参数
    try:
        p = int(p)
        other_id = int(other_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    # 3.业务逻辑处理
    # 根据other_id,查出其它用户模型
    try:
        other = User.query.get(other_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据查询出错')

    if not other:
        abort(404)

    news_list = []
    current_page = 0
    total_page = 0
    # 根据其它用户的模型,去查询用户发布的新闻信息,并分页
    try:
        paginate = other.news_list.paginate(p, constants.OTHER_NEWS_PAGE_MAX_COUNT, False)
        news_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据查询出错')

    new_dict_li = []
    for new in news_list:
        new_dict_li.append(new.to_dict())

    data = {
        'news_list': new_dict_li,
        'current_page': current_page,
        'total_page': total_page
    }

    # 4.返回结果
    return jsonify(errno=RET.OK, errmsg='OK', data=data)


@profile_blu.route('/other_info')
@set_func
def other_info():
    """
    其他用户信息展示
    :return:
    """
    user = g.user
    if not user:
        return render_template('news/other.html', errmsg='用户未登录')

    # 1.接收用户id
    other_id = request.args.get('user_id')

    # 2.校验参数
    try:
        other_id = int(other_id)
    except Exception as e:
        current_app.logger.error(e)

    other = None
    # 3.业务逻辑处理
    # 根据用户的id,去查询用户的详细信息
    try:
        other = User.query.get(other_id)
    except Exception as e:
        current_app.logger.error(e)

    if not other:
        abort(404)

    # 是否关注
    is_followed = False
    # 如果其它用户存在,并且user(用户)已经登录
    if other and user:
        # 如果其他用户在当前登录的用户的关注列表中
        if other in user.followed:
            is_followed = True

    data = {
        'user_info': user.to_dict(),
        'other_info': other.to_dict(),
        'is_followed': is_followed
    }

    return render_template('news/other.html', data=data)


@profile_blu.route('/user_follow', methods=['POST', 'GET'])
@set_func
def user_follow():
    """
    我的关注
    :return:
    """
    user = g.user

    # 1.接收参数
    p = request.args.get('p', 1)  # p 页数

    # 2.校验参数
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    # 设置默认值
    user_list = []
    current_page = 0
    total_page = 0

    # 3.业务逻辑处理
    try:
        # 查询用户关注过的所有人
        paginate = user.followed.paginate(p, constants.USER_FOLLOWED_MAX_COUNT, False)
        # 获取具体的数据
        user_list = paginate.items
        # 获取当前页数
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据查询错误')

    # 把对象列表转成对象字典
    user_dict_li = []
    for user in user_list:
        user_dict_li.append(user.to_dict())

    data = {
        'users': user_dict_li,
        'current_page': current_page,
        'total_page': total_page
    }


    return render_template('news/user_follow.html', data=data)

@profile_blu.route('/news_list')
@set_func
def news_list():
    """
    用户发布的新闻列表
    :return:
    """
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录')
    # 1.获取参数
    page = request.args.get('p', 1)

    # 2.校验参数
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    # 3．业务逻辑处理
    # 设置默认参数
    news_release_list = []
    current_page = 0
    total_page = 0

    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(page, constants.OTHER_NEWS_PAGE_MAX_COUNT, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据查询错误')

    # 获取查询数据
    news_list = paginate.items
    total_page = paginate.pages  # 总页数
    current_page = paginate.page

    news_dict_li = []
    for new in news_list:
        news_dict_li.append(new.to_review_dict())



    data={
        'news_list': news_dict_li,
        'current_page': current_page,
        'total_page': total_page
    }

    return render_template('news/user_news_list.html', data=data)


@profile_blu.route('/news_release', methods=['post', 'get'])
@set_func
def news_release():
    """
    新闻发布
    :return:
    """

    if request.method == 'GET':
        try:
            categories = Category.query.all()  # 查询新闻分类表
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg='数据查询错误')

        category_dict_li = []
        for new in categories:
            category_dict_li.append(new.to_dict())

        category_dict_li.pop(0)  # 把最新分类删除
        data = {
            'categories': category_dict_li
        }
        return render_template('news/user_news_release.html', data=data)



    # 1.接收参数, 接收参数
    title = request.form.get('title')  # 新闻标题  获取不到值的原因是,表单中,有name属性的才会被提交
    category_id = request.form.get('category_id')  # 新闻分类id
    digest = request.form.get('digest')  # 新闻摘要
    content = request.form.get('content') # 新闻内容
    index_image = request.files.get('index_image')



    # 2.校验参数
    if not all([title, category_id, digest,  content]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')


    # 1.2 尝试读取图片
    try:
        index_image = index_image.read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")


        # 2. 将标题图片上传到七牛
    try:
        key = storage(index_image)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传图片错误")

    # 3.初始化数据模型,把数据保存到数据库中中
    # 初始化新闻表模型
    news = News()
    news.title = title
    news.source = "原创"
    news.category_id = category_id
    news.digest = digest
    news.content = content
    news.user_id = g.user.id
    news.status = 1
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + key




    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据保存失败')


    return jsonify(errno=RET.OK, errmsg="发布成功")


@profile_blu.route('/collection')
@set_func
def user_collection():
    """
    用户收藏的新闻列表
    因为只是显示数据,没有对数据的修改,所以使用get请求
    :return:
    """

    # 1.因为要显示所有的收藏新闻,所以要获取页数
    p = request.args.get('p', 1)

    # 2.校验参数
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    current_page = 1
    total_page  = 1
    user = g.user
    # 3.业务逻辑处理
    # 根据获取的新闻id查询新闻
    try:
        # paginate(当前页数,一页显示多少条数据,是否有错误输出:默认为True)
        paginate = user.collection_news.paginate(p, constants.USER_COLLECTION_MAX_NEWS, False)
        # 获取当前查询的数据, 查出来的是一个列表对象
        collections = paginate.items
        # 获取的当前页数
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)



    collection_li = []
    for new in collections:
        collection_li.append(new.to_basic_dict())

    data = {
        'collections': collection_li,
        'current_page': current_page,
        'total_page': total_page
    }

    return render_template('news/user_collection.html', data=data)


@profile_blu.route('/pass_info', methods=['POST', 'GET'])
@set_func
def pass_info():
    """
    修改密码
    :return:
    """
    user = g.user

    if request.method == 'GET':
        return render_template('news/user_pass_info.html')

    # 1.接收参数
    params = request.json
    old_password = params.get('old_password')
    new_password = params.get('new_password')

    # 2.校验参数
    if not all([old_password, new_password]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    # 3.业务逻辑处理
    # 检查输入的旧密码是否正确

    if not user.check_passowrd(old_password):
        return jsonify(errno=RET.PWDERR, errmsg='旧密码输入错误')

    # 如果旧密码输入正确
    user.password = new_password

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)


    return jsonify(errno=RET.OK, errnsg='修改成功')


@profile_blu.route('/pic_info', methods=['POST', 'GET'])
@set_func
def pic_info():
    """
    修改头像
    :return:
    """

    user = g.user
    if request.method == 'GET':
        data = {
            'user_info': user.to_dict()
        }
        return render_template('news/user_pic_info.html', data=data)

    # 1.接收参数,要上传的头像
    try:
        avatar = request.files.get('avatar').read()  # 获取头像,并把头像转成二进制文件
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='读取文件错误')

    # 把头像上传到七牛
    try:
        url = storage(avatar)  # 获取到的是key
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg='上传图片错误')

    # 将头像的变更保存到数据库中
    user.avatar_url = url

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg='文件保存失败')

    data={
        'avatar_url':constants.QINIU_DOMIN_PREFIX + url
    }

    return jsonify(errno=RET.OK, errmsg='修改成功', data=data)


@profile_blu.route('/base_info', methods=['POST', 'GET'])
@set_func
def base_info():
    """
    修改个人信息
    :return:
    """
    user = g.user
    # 如果是GET请求,是来获取用户个人信息
    if request.method == 'GET':
        data = {
            'user_info':user.to_dict()
        }
        return render_template('news/user_base_info.html', data=data)

    # 如果是post请求,是修改个人信息
    else:
        # 1.接收参数 注:接收三个参数,用户昵称,个性签名,性别
        params = request.json
        nick_name = params.get('nick_name')
        signature = params.get('signature')
        gender = params.get('gender')

        # 2.校验参数
        if not all([nick_name, signature, gender]):
            return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

        if gender not in ('MAN','WOMEN'):
            return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

        # 3.业务逻辑处理
        try:
            user = User.query.get(user.id)  # 查询出user模型对象
            user.nick_name = nick_name
            user.signature = signature
            user.gender = gender
        except Exception as e:
            current_app.logger.error(e)

        try:
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            db.session.rollback()
            return jsonify(errno=RET.DBERR, errmsg='数据保存失败')


        return jsonify(errno=RET.OK, errmsg='修改成功')


@profile_blu.route('/info')
@set_func
def user_info():

    """
    用户个人资料显示
    :return:
    """

    user = g.user

    if not user:  # 如果用户未登录
        return redirect('/')  # 重定向到首页

    data = {
        'user_info':user.to_dict(),

    }
    return render_template('news/user.html', data=data)